/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2015 All Rights Reserved.
 */
package com.nuanshui.heatedloan.extension.interceptor;

import com.nuanshui.framework.utils.LogUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LogUtilInterceptor implements HandlerInterceptor {

    /** 
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //LogUtil.myThreadStart(null);
        PerfLog.printStart(getMethodStr(handler) + "(WEB):" + request.getServletPath());
        return true;
    }

    /** 
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        PerfLog.printEnd(getMethodStr(handler) + "(WEB):" + request.getServletPath());
       // LogUtil.myThreadEnd();
    }

    /** 
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        if (LogUtil.getUniqueId() != null) {
            PerfLog.printEnd(getMethodStr(handler) + "(WEB):" + request.getServletPath());
            //LogUtil.myThreadEnd();
        }
    }

  
    private String getMethodStr(Object handler) {
        String className;
        String methodName;
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            className = hm.getBean().getClass().getName();
            methodName = hm.getMethod().getName();
        } else {
            className = "";
            methodName = "";
        }

        return className + "." + methodName;
    }

}
